package com.study.testSpringBoot.download;

import cn.hutool.core.lang.UUID;
import com.obs.services.ObsClient;
import com.obs.services.model.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

public class HuaWeiStorageUtil {

    private static ObsClient createObsClient(){
//        obs.endpoint: obs.cn-east-2.myhuaweicloud.com  obs.sk: hgwPifCqVO9uMw5cBZH1mJUjraOXk19ecFVCvFPw
//        obs.ak: CE8VVPAZZC3QJRYICFXD
//        String endPoint = "obs.cn-north-1.myhwclouds.com";
//        String ak = "CE8VVPAZZC3QJRYICFXD";
//        String sk = "hgwPifCqVO9uMw5cBZH1mJUjraOXk19ecFVCvFPw";
        String endPoint = "obs.cn-east-2.myhuaweicloud.com";
        String ak = "QIYRDMKHORR9XSRNNDGD";
        String sk = "j0MPo7GYdEMv0HUdVt8cWvMfc3Mv8hCIIvzveCoP";
//        String endPoint = PropertiesUtil.getProperty("obs.endpoint");
//        String ak = PropertiesUtil.getProperty("obs.ak");
//        String sk = PropertiesUtil.getProperty("obs.sk");
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        return obsClient;
    }
    private static void closeObsClient(ObsClient obsClient){
        try {
            obsClient.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
    public static void createBucket(String bucketName){
        ObsClient obsClient = createObsClient();
        ObsBucket bucket = obsClient.createBucket(bucketName);
        closeObsClient(obsClient);
    }

    public static void uploadFile(String bucketName, String objectKey,String filePath){
        ObsClient obsClient = createObsClient();
        obsClient.putObject(bucketName,objectKey, new File(filePath));
        closeObsClient(obsClient);
    }

    public static File downloadFile(String bucketName, String objectKey, String filePath,boolean isPic){
        ObsClient obsClient = createObsClient();
        ObsObject object = null;
        if(isPic){
            GetObjectRequest getObjectRequest = new GetObjectRequest();
            getObjectRequest.setBucketName(bucketName);
            getObjectRequest.setObjectKey(objectKey);
            getObjectRequest.setImageProcess("image/resize,m_lfit,h_512,w_512");
            object = obsClient.getObject(getObjectRequest);
        }else {
            object = obsClient.getObject(bucketName, objectKey);
        }
        InputStream content = object.getObjectContent();
        try {
            File destination = new File(filePath);
            FileUtils.copyInputStreamToFile(content, destination);
            return destination;
        } catch(IOException e) {
            e.printStackTrace();
        }

        closeObsClient(obsClient);
        return null;
    }
    public static File downloadFile(String bucketName, String objectKey, String filePath,String imageProcess){
        ObsClient obsClient = createObsClient();
        ObsObject object = null;
        if(StringUtils.isNotBlank(objectKey)&&(StringUtils.endsWithIgnoreCase(objectKey, "png")
        ||StringUtils.endsWithIgnoreCase(objectKey, "jpg")||StringUtils.endsWithIgnoreCase(objectKey, "jpeg"))){
            GetObjectRequest getObjectRequest = new GetObjectRequest();
            getObjectRequest.setBucketName(bucketName);
            getObjectRequest.setObjectKey(objectKey);
            getObjectRequest.setImageProcess(imageProcess);
            object = obsClient.getObject(getObjectRequest);
        }else {
            object = obsClient.getObject(bucketName, objectKey);
        }
        InputStream content = object.getObjectContent();
        try {
            File destination = new File(filePath);
            FileUtils.copyInputStreamToFile(content, destination);
            return destination;
        } catch(IOException e) {
            e.printStackTrace();
        }

        closeObsClient(obsClient);
        return null;
    }





    public static void deleteFile(String bucketName,String objectKey){
        ObsClient obsClient = createObsClient();
        HeaderResponse response = obsClient.deleteObject(bucketName, objectKey);

        closeObsClient(obsClient);
    }
    /**
     * 获取私有桶里的文件的地址
     * @param  bucketName
     * @param fileName
     * @return
     */
    public static String getPrivateDownloadPath(String bucketName,String fileName) {
        // URL有效期，3600秒
        long expireSeconds = 60 * 60 * 24 * 6;
        String url = "" ;
//        RedisTemplate bean = (RedisTemplate) BeanFactory.getBean(StringRedisTemplate.class);
//        ValueOperations<String,String> operations = bean.opsForValue();
//        url = operations.get("obs"+bucketName+fileName);
//        if(StringUtils.isBlank(url)) {
//            ObsClient obsClient = createObsClient();
//            // 创建桶
//            TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expireSeconds);
//            TemporarySignatureResponse response = null;
//            try {
//                request.setBucketName(bucketName);
//                request.setObjectKey(fileName);
//                response = obsClient.createTemporarySignature(request);
//                url = response.getSignedUrl();
//                System.out.println(url);
//                obsClient.close();
//                operations.set("obs"+bucketName+fileName,url,expireSeconds, TimeUnit.SECONDS);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        return  url;
    }

    /**
     * 公共桶文件下载地址
     * @param objectKey
     * @return
     */
    public static String getPublicDownloadPathThumb(String objectKey) {
//        return PropertiesUtil.getProperty("obs.download.url") +  objectKey;
        return "" +  objectKey;
    }
    /**
     * 上传文件
     *
     * @param fileName
     * @param file
     * @throws IOException
     */
    public static String upload(String bucketName,String fileName, File file)  {
        return upload( bucketName, fileName, null, file);
    }
    /**
     * 上传文件
     *
     * @param fileName
     * @param file
     * @throws IOException
     */
    public static String upload(String bucketName,String fileName, String folder,File file)  {
        String extension = FilenameUtils.getExtension(fileName);

        String objectKey = (StringUtils.isNotBlank(folder)?folder+"/":"")+UUID.randomUUID().toString()+(StringUtils.isNotBlank(extension)?"."+extension:"");
        try {
            ObsClient obsClient = createObsClient();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.addUserMetadata("originalFileName",fileName);
            if(file.getName().endsWith("gz")){
                metadata.setContentType("application/json");
                metadata.setContentEncoding("gzip");
            }
            obsClient.putObject(bucketName, objectKey, file,metadata);
            System.out.println("Put object:" + fileName + " successfully.");
            obsClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return objectKey;
    }
    /**
     * 上传文件
     *
     * @param bucketName
     * @param fileName
     * @param inputStream
     * @throws IOException
     */
    public static String upload(String bucketName,String fileName, InputStream inputStream)  {
        return upload( bucketName, fileName, null, inputStream);
    }

    /**
     * 上传文件
     *
     * @param fileName
     * @param inputStream
     * @throws IOException
     */
    public static String upload(String bucketName,String fileName, String folder,InputStream inputStream)  {
        String extension = FilenameUtils.getExtension(fileName);
        String objectKey = (StringUtils.isNotBlank(folder)?folder+"/":"")+UUID.randomUUID().toString()+(StringUtils.isNotBlank(extension)?"."+extension:"");
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.addUserMetadata("originalFileName",fileName);
        ObsClient obsClient = createObsClient();
        obsClient.putObject(bucketName, objectKey, inputStream,metadata);
        System.out.println("Put object:" + fileName + " successfully.");
        closeObsClient(obsClient);
        return objectKey;
    }

    public static void copyFile(String sourceBucket,String sourceObjectKey,String destinationBucketName){
        ObsClient obsClient = createObsClient();
        CopyObjectRequest copyObjectRequest = createCopyObjectRequest(sourceBucket,sourceObjectKey,destinationBucketName);
        obsClient.copyObject(copyObjectRequest);
        closeObsClient(obsClient);
    }
    private static CopyObjectRequest createCopyObjectRequest(String sourceBucket,String sourceObjectKey,String destinationBucketName){
        CopyObjectRequest copyObjectRequest = new CopyObjectRequest();
        copyObjectRequest.setSourceBucketName(sourceBucket);
        copyObjectRequest.setSourceObjectKey(sourceObjectKey);
        copyObjectRequest.setDestinationBucketName(destinationBucketName);
        copyObjectRequest.setDestinationObjectKey(sourceObjectKey);
        return copyObjectRequest;
    }
}
